﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CF.Data.Entity.FrmMemberEntity;

namespace CF.Member.DAL.Member
{
    public class FM_MemberBindingDAL
    {
        caifendbEntities context;

        public FM_MemberBindingDAL()
        {
            context = new caifendbEntities();
        }

        ~FM_MemberBindingDAL()
        {
            context.Dispose();
        }

        /// <summary>
        /// 添加微博授权时间，同步有效时间
        /// </summary>
        /// <param name="addObj"></param>
        /// <returns></returns>
        public void AddMemberBinding(int uid, string bindUid, string type, string accesstoken, int expires)
        {
            try
            {
                FM_MemberBinding addObj = new FM_MemberBinding()
                {
                    UID = uid,
                    BindOtherUID = bindUid,
                    BindType = type,
                    BindTime = DateTime.Now,
                    AccessToken = accesstoken,
                    Expires_in = expires,
                    EffectiveTime = DateTime.Now.AddSeconds(expires)
                };
                context.AddToFM_MemberBinding(addObj);
                context.SaveChanges();
            }
            catch { 
                //出错都无所大谓，所以暂时不做处理！
            }

        }

        /// <summary>
        /// 检查是否同步在有效时间AccessToken 时间范围内。
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="bindUid"></param>
        /// <param name="type"></param>
        /// <param name="accesstoken"></param>
        /// <param name="expires"></param>
        public void CheckMemberBinding(int uid, string bindUid, string type, string accesstoken, int expires)
        {
            try
            {
                var query = context.FM_MemberBinding.Where(c => c.UID == uid && c.BindOtherUID == bindUid && c.BindType == type).First();
                if (query.AccessToken != accesstoken)
                {
                    query.AccessToken = accesstoken;
                    query.Expires_in = expires;
                    query.EffectiveTime = DateTime.Now.AddSeconds(expires);
                    context.SaveChanges();
                }
            }
            catch {
             //出错都无所大谓，所以暂时不做处理！
            }

        }

    }
}
